<?php

define('IN',1);

require_once 'common.inc.php';
needLogin();
require_once __PATH__.'/source/function/function_cart.php';


$allow = array('list','add','delete','update','clean','flow','submit','succeed');
$act = in_array($_GET['act'],$allow) ? $_GET['act'] : $allow['0'];

$pclass = array();
foreach ($product_class as $class) {
    if ($class['parent_id']==0) {
        $pclass[] = $class;
    }
}
$template->pclass = $pclass;


if ($_G['state']!=1) {
    $msg = '您是待审核用户还不能执行下单等操作，请联系客服进行审核';
    if (AJAX) {
        outputJson(0,$msg);
    } else {
        exit($msg);
    }
}

if ('list' == $act) {## 查看购物车
    $product_list = $_ENV['db']->fetchAll("SELECT * FROM cart WHERE `uid` = '{$_G['uid']}'");
    $cart = array();
    if ($product_list) {
        $pids = array(0);
        foreach ($product_list as $product) {
            $pids[] = $product['product_id'];
            $cart[$product['product_id']] = $product['num'];
        }

        $product_list = $_ENV['db']->fetchAll("SELECT * FROM product as p left join product_image as i on p.default_imagehash=i.hash where p.product_id in (".implode(',',$pids).")");
    }
    $template->products = $product_list;
    $template->cartnum = $cart;
    $template->addScript('cart_step1');
    showMainFrontPage('front/cart_list');
} else if('update' == $act) {## 更新购物车
    $product = $_POST['product'];
    foreach ((array)$product as $pid=>$d) {
        $_ENV['db']->runSql("UPDATE cart SET num = '{$d}' WHERE uid = '{$_G['uid']}' and product_id = '{$pid}'");
    }
    echo json_encode(array('message'=>''));
} else if('flow' == $act) {
    // 获取购物车商品信息
    $products = $_ENV['db']->fetchAll("SELECT * FROM cart WHERE `uid` = '{$_G['uid']}'");
    $template->products = $products;
    // 获取收货地址信息
    $rlist = $_ENV['db']->fetchAll("SELECT * FROM customer_receive where customer_id = '{$_G['cid']}'");
    $template->rlist = $rlist;
    // 获取发票信息
    $flist = $_ENV['db']->fetchAll("SELECT * FROM fapiao where uid = '{$_G['cid']}'");
    $template->flist = $flist;
    showMainFrontPage('front/cart_flow');
} else if ('add' == $act) {## 添加到购物车
    cartAddProduct($_GET['pid']);
    outputJson(1,'添加成功');
} else if('delete' == $act) {## 删除指定商品
    $_ENV['db']->runSql("DELETE FROM cart WHERE uid = '{$_G['uid']}' and product_id = '".(int)$_GET['pid']."'");
} else if('clean' == $act) {
    $_ENV['db']->runSql("DELETE FROM `cart` WHERE `uid` = '{$_G['uid']}'");
} else if('submit' == $act && POST && AJAX) {
    // 获取购物车中所有商品id
    $pid = array(0);
    $cart_products = $_ENV['db']->fetchAll("SELECT * FROM cart WHERE uid = '{$_G['uid']}'");
    if (!$cart_products) {
        outputJson(0,'您的购物车中没有商品，请先添加商品到购物车');
    }

    // 获取收货地址信息
    $receive = $_ENV['db']->fetch("SELECT * FROM customer_receive WHERE cr_id = '{$_POST['rid']}' and customer_id = '{$_G['cid']}'");
    if (!$receive) {
        outputJson(0,'请选择收货地址');
    }
    // 获取发票信息
    $fapiao = $_ENV['db']->fetch("SELECT * FROM fapiao WHERE fid = '{$_POST['fid']}' and uid = '{$_G['cid']}'");
    if (!$fapiao) {
        outputJson(0,'请选择发票信息');
    }

    foreach ($cart_products as $c) {
        $pid[$c['product_id']] = $c['num'];
    }

    //获取指定商品
    $products = $_ENV['db']->fetchAll("SELECT * FROM product WHERE product_id in (".implode(',',array_keys($pid)).")");
    // 生成订单号
    $order_sn = makeOrderId();
    // 插入订单总表
    $sql = "INSERT INTO `order` ".buildSql(array(
            'customer_id' => $_G['uid'],        //客户下领导人ID
            'customer_name' => $_G['username'], //领导人名字
            'order_sn' => $order_sn,
            'address' => $receive['address'],
            'tel' => $receive['tel'],
            'zip' => $receive['zip'],
            'username' => $receive['receive_name'],
            'audit_state' => '0',
            'price' => '0',
            'pprice' => '0',
            'payed' => '0',
            'created_time' => time(),
            'last_time' => time(),
            'fp_name' => $fapiao['name'],
            'fp_tt' => $fapiao['tt'],
            'fp_nr' => $fapiao['nr']
        ));
    $_ENV['db']->runSql($sql);
    $order_id = $_ENV['db']->insertId();
    if (!$order_id) outputJson(0,'订单提交失败请联系我们了解详情[ID错误]');

    // 统计商品信息并且拼装SQL
    $tprice = 0;
    foreach ((array)$products as $product) {
        # 商品总价
        $ttprice = $product['price']*$pid[$product['product_id']];
        # 所有商品总价
        $tprice += $ttprice;
        $sql = "INSERT INTO order_detail ".buildSql(array(
                'order_id' => $order_id,
                'order_sn' => $order_sn,
                'product_id' => $product['product_id'],
                'product_name' => $product['name'],
                'product_price' => $product['price'],
                'product_pprice' => '0',
                'product_num' => $pid[$product['product_id']],
                'product_total_price' => $ttprice,
                'product_total_pprice' => '0',
                'created_time' => time()
            ));
        $_ENV['db']->runSql($sql);
    }
    $_ENV['db']->runSql("UPDATE `order` ".buildSql(array('price'=>$tprice))." where order_id = '{$order_id}'");
    // 插入记录
    $_ENV['db']->runSql("INSERT INTO order_history ".buildSql(array(
            'order_sn' => $order_sn,
            'username' => $_G['username'],
            'desc' => "{$_G['username']}通过网站下单",
            'timestamp' => time()
        )));
		
	//更新客户的下单个数
	$_ENV['db']->runSql("UPDATE `customer` set ordersum=ordersum+1 where customer_id = '{$_G['cid']}'");
	//更新当前操作人的下单个数	
	$_ENV['db']->runSql("UPDATE `customer_leader` set ordersum=ordersum+1 where leader_id = '{$_G['uid']}'");	
		
    // 清空购物车
    $_ENV['db']->runSql("DELETE FROM cart WHERE uid = '{$_G['uid']}'");

    outputJson(1,'操作成功',$order_sn);
} else if ('succeed' == $act) {
    showMainFrontPage('front/succeed');
}